<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue' // 骨架屏
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { homeBannerAPI, homeCategoryAPI, homeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'

// 获取顶部轮播图
const bannerList = ref<BannerItem[]>([])
const getBannerList = async () => {
  const res = await homeBannerAPI()
  bannerList.value = res.result
}
// 获取分类
const categoryList = ref<CategoryItem[]>([])
const getCategoryList = async () => {
  const res = await homeCategoryAPI()
  categoryList.value = res.result
}
// 获取热门推荐
const hotList = ref<HotItem[]>([])
const getHotList = async () => {
  const res = await homeHotAPI()
  hotList.value = res.result
}

const guessRef = ref<XtxGuessInstance>()
// 滚动触底
const onScrollTolower = () => {
  console.log(`滚动触底 -->`, 1)
  // 触底的时候调用组件的加载更多
  guessRef.value?.getMore()
}
// 下拉刷新
const isRefresh = ref(false)
const onRefresherrefresh = async () => {
  isRefresh.value = true
  await Promise.all([getBannerList(), getCategoryList(), getHotList(), guessRef.value?.resetData()])
  // 刷新的时候调用组件的重新加载
  guessRef.value?.getMore()
  isRefresh.value = false
}
// 是否加载中
const isLoading = ref(false)

// 生命周期
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBannerList(), getCategoryList(), getHotList()])
  isLoading.value = false
})
</script>

<template>
  <!-- 顶部栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    refresher-enabled
    class="scroll-view"
    scroll-y
    :refresher-triggered="isRefresh"
    @scrolltolower="onScrollTolower"
    @refresherrefresh="onRefresherrefresh"
  >
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
//
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.scroll-view {
  flex: 1;
}
</style>
